package com.simple.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ReportUtil {

	private static final long TIME24 = 24 * 60 * 60 * 1000;

	private static final long TIME235959 = (24 * 60 * 60 - 1) * 1000;

	public static String dealReportIterator(String rep, String endDateStr) {
		if (StringUtils.isEmpty(rep)) {
			return rep;
		}
		try {
			//传入2019-12-28
			long queryEnd = DateUtil.getEndTimeLongYYMMDD(endDateStr);
			JSONObject jsonObj = JSONObject.parseObject(rep);
			String code = jsonObj.getString("msgCode");
			if ("302".equals(code)) {
				JSONArray newdataArr = new JSONArray();
				JSONObject dataObj = jsonObj.getJSONObject("data");
				JSONArray dataArr = dataObj.getJSONArray("data");
				Iterator iterator = dataArr.iterator();
				while (iterator.hasNext()) {
					JSONObject data = (JSONObject) iterator.next();
					long start = data.getLongValue("start");
					// long duration = data.getLongValue("duration");
					// Date datetime = data.getDate("datetime");
					long end = data.getLongValue("end");
					Date endDt = new Date(end);
					Date startDt = new Date(start);
					// 当天23:59:59
					Date curEnd = DateUtil.getEndTime(startDt);
					long curEndtime = curEnd.getTime();
					Date curStart = DateUtil.getStartTime(startDt);
					// 当天00:00:00
					long curStarttime = curStart.getTime();
					if (endDt.after(curEnd)) {
						long moretime = end - curEndtime;
						long mod = moretime % TIME24;
						int day = (int) (mod == 0 ? moretime / TIME24 : moretime / TIME24 + 1);
						//倒序
						for (int i = day-1; i >= 0; i--) {
							// 00:00:00
							long addDayStart = curStarttime + TIME24 * (i+1);
							long addDur = TIME24;
							// 23:59:59
							long addDayEnd = addDayStart + TIME235959;
							if (addDayStart <= queryEnd) {
								JSONObject newdata = (JSONObject) data.clone();
								if (i == day - 1) {
									addDur = mod == 0 ? TIME24 : mod;
									addDayEnd = mod == 0 ? addDayEnd : (addDayStart + mod);
								}
								newdata.put("start", addDayStart);
								newdata.put("duration", addDur);
								newdata.put("end", addDayEnd);
								newdata.put("datetime", DateUtil.Long2String(addDayStart));
								newdata.put("time", addDayStart);
								newdataArr.add(newdata);
							}
						}
						
						// 新的间隔时间 当天结束
						long newduration = curEndtime - start;
						data.put("duration", newduration);
						data.put("end", curEndtime);
						newdataArr.add(data);
					}else {
						newdataArr.add(data);
					}
					
				}
				if (newdataArr.size() > 0) {
					dataObj.put("data", newdataArr);
					dataObj.put("count",newdataArr.size());
				}
			}
			return jsonObj.toJSONString();

		} catch (Exception e) {
			e.printStackTrace();
			return rep;
		}

	}

	
	
	
	//有数据时间交叉   处理
	public static String dealReportData(String rep, String endDateStr) {
		if (StringUtils.isEmpty(rep)) {
			return rep;
		}
		try {
			//传入2019-12-28
			long queryEnd = DateUtil.getEndTimeLongYYMMDD(endDateStr);
			JSONObject jsonObj = JSONObject.parseObject(rep);
			String code = jsonObj.getString("msgCode");
			if ("302".equals(code)) {
				//JSONArray newdataArr = new JSONArray();
				List<JSONObject> newdataArr = new ArrayList<>();
				JSONObject dataObj = jsonObj.getJSONObject("data");
				JSONArray dataArr = dataObj.getJSONArray("data");
				for(int index = 0 ;index<dataArr.size(); index++) {
					
					JSONObject data = dataArr.getJSONObject(index);
					JSONObject cloneData = (JSONObject) data.clone();
					
					long start = data.getLongValue("start");
					// long duration = data.getLongValue("duration");
					// Date datetime = data.getDate("datetime");
					long end = data.getLongValue("end");
					Date endDt = new Date(end);
					if(index < dataArr.size()-1) {
						JSONObject lastData = dataArr.getJSONObject(index + 1);
						long lastEnd = lastData.getLongValue("end");
						//是否同一天 且   开始时间  小于  上一次结束时间
						String lastEndStr = DateUtil.Long2String2(lastEnd);
						String startStr =  DateUtil.Long2String2(start);
						if(lastEnd > start && lastEndStr.equals(startStr)) {
							start = lastEnd;
							cloneData.put("start", start);
						}
						
					}
					Date startDt = new Date(start);
					// 当天23:59:59
					Date curEnd = DateUtil.getEndTime(startDt);
					long curEndtime = curEnd.getTime();
					Date curStart = DateUtil.getStartTime(startDt);
					// 当天00:00:00
					long curStarttime = curStart.getTime();
					if (endDt.after(curEnd)) {
						long moretime = end - curEndtime;
						long mod = moretime % TIME24;
						int day = (int) (mod == 0 ? moretime / TIME24 : moretime / TIME24 + 1);
						//倒序  插入数据  
						for (int i = day-1; i >= 0; i--) {
							// 00:00:00
							long addDayStart = curStarttime + TIME24 * (i+1);
							long addDur = TIME24;
							// 23:59:59
							long addDayEnd = addDayStart + TIME235959;
							if (addDayStart <= queryEnd) {
								JSONObject newdata = (JSONObject) data.clone();
								if (i == day - 1) {
									addDur = mod == 0 ? TIME24 : mod;
									addDayEnd = mod == 0 ? addDayEnd : (addDayStart + mod);
								}
								newdata.put("start", addDayStart);
								newdata.put("duration", addDur);
								newdata.put("end", addDayEnd);
								newdata.put("datetime", DateUtil.Long2String(addDayStart));
								newdata.put("time", addDayStart);
								newdataArr.add(newdata);
							}
						}
						
						// 新的间隔时间 当天结束
						long newduration = curEndtime - start;
						cloneData.put("duration", newduration);
						cloneData.put("end", curEndtime);
						newdataArr.add(cloneData);
					}else {
						newdataArr.add(cloneData);
					}
					// 数据List 排序  按start时间    倒序
					Collections.sort(newdataArr, new Comparator<JSONObject>() {
						@Override
						public int compare(JSONObject o1, JSONObject o2) {
							return (int)(o2.getLong("start") - o1.getLong("start"));
						}
					}); 
				}
				if (newdataArr.size() > 0) {
					dataObj.put("data", newdataArr);
					dataObj.put("count",newdataArr.size());
					dataObj.put("pageSize",newdataArr.size());
				}
			}
			return jsonObj.toJSONString();

		} catch (Exception e) {
			e.printStackTrace();
			return rep;
		}

	}
	
	
	public static String doStatisticsData(String dataUrl,String machine_no,String end_date) {
		String nextStart = null;
		JSONArray colData = new JSONArray();
		long querySt = DateUtil.getStartTimeLongYYMMDD(end_date);
		//最多查询500条
		for(int i=0; i<5; i++) {
			Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
			paramMap.put("machine_no", machine_no);
			paramMap.put("pageSize", 100);
			paramMap.put("nextStart", nextStart);
			paramMap.put("end_date", end_date);
			String res = "";//HttpClientUtil.sendGet(dataUrl, paramMap);
			if (StringUtils.isEmpty(res)) {
				return res;
			}
			JSONObject jsonObj = JSONObject.parseObject(res);
			String code = jsonObj.getString("msgCode");
			if ("302".equals(code)) {
				JSONObject dataObj = jsonObj.getJSONObject("data");
				nextStart = dataObj.getString("nextStart");
				JSONArray dataArr = dataObj.getJSONArray("data");
				colData.addAll(dataArr);
				if(dataArr != null && dataArr.size()>0) {
					int size = dataArr.size();
					JSONObject lastObj = dataArr.getJSONObject(size - 1);
					long lastSt = lastObj.getLongValue("start");
					//排序数据已经  有所有的当前日期的数据     最后一条数据  已经小于  查询时间00:00:00
					if(lastSt < querySt) {
						break;
					}
				}
			}
		}
		JSONObject jsonStat = new JSONObject();
		JSONObject colObj = new JSONObject();
		colObj.put("data", colData);
		colObj.put("count", colData.size());
		colObj.put("pageSize", colData.size());
		colObj.put("nextStart", nextStart);
		
		jsonStat.put("data", colObj);
		jsonStat.put("field", null);
		jsonStat.put("message", "获取数据成功");
		jsonStat.put("msgCode", "302");
		
		return doStatistics(jsonStat.toJSONString(),end_date);
	}
	
	
	
	
	
	
	//统计数据
	public static String doStatistics(String rep, String queryDate) {
		try {
			//先做数据处理
			rep = dealReportData(rep, queryDate);
			if (StringUtils.isEmpty(rep)) {
				return rep;
			}
			//传入2019-12-28
			long queryEnd = DateUtil.getEndTimeLongYYMMDD(queryDate);
			long queryStart = DateUtil.getStartTimeLongYYMMDD(queryDate);
			JSONObject jsonObj = JSONObject.parseObject(rep);
			JSONObject jsonStat = new JSONObject();
			String code = jsonObj.getString("msgCode");
			if ("302".equals(code)) {
				JSONObject dataObj = jsonObj.getJSONObject("data");
				JSONArray dataArr = dataObj.getJSONArray("data");
				Map<String,Map<String,Object>> stat = new ConcurrentHashMap<>();
				Map<String,Object> total = new HashMap<>();
				int totalCount = 0;
				long totalDuration = 0;
				for(int index = 0 ;index<dataArr.size(); index++) {
					JSONObject data = dataArr.getJSONObject(index);
	                String appName = data.getString("appName");		
	                String activityName = data.getString("activityName");
	                String packageName = data.getString("packageName");
	                long duration = data.getLongValue("duration");
	                long start = data.getLongValue("start");
	                long end = data.getLongValue("end");
	                //存在 当天内
	                if(start >= queryStart && start <= queryEnd) {
	                	Map<String,Object> statMap = stat.get(appName);
	                	if(null == statMap) {
	                		statMap = new ConcurrentHashMap<>();
	                	}
	                	long durationEx = Long.parseLong(statMap.get("duration")!=null?statMap.get("duration").toString():"0");
	                	int countEx = Integer.parseInt(statMap.get("count")!=null?statMap.get("count").toString():"0");
	                	totalCount++;
	                	countEx++;
	                	durationEx = durationEx + duration;
	                	totalDuration = totalDuration + duration;
	                	long startEx = Long.parseLong(statMap.get("start")!=null?statMap.get("start").toString():"0");
	                	if(start < startEx  || startEx == 0) {
	                		statMap.put("start", start);
	                	}
	                	long endEx = Long.parseLong(statMap.get("end")!=null?statMap.get("end").toString():"0");
	                	if(end > endEx || endEx == 0) {
	                		statMap.put("end", end);
	                	}
	                	statMap.put("appName", appName);
	                	statMap.put("duration", durationEx);
	                	statMap.put("count", countEx);
	                	statMap.put("packageName", packageName);
	                	statMap.put("type", 0);
	                	statMap.put("activityName", activityName);
	                	stat.put(appName, statMap);
	                }
				}
				total.put("appName", "TotalDuration");
				total.put("duration", totalDuration);
				total.put("count", totalCount);
				total.put("packageName", "TotalDuration");
				total.put("type", 0);
				total.put("activityName", null);
				total.put("start", null);
				total.put("end", null);
				List<Map<String,Object>> statData = new ArrayList<>();
				//排第一个
				statData.add(total);
				for(String key : stat.keySet()) {
					statData.add(stat.get(key));
				}
				//重新构造data 数据
				JSONObject dataStat = new JSONObject();
				dataStat.put("data", statData);
				dataStat.put("message", "获取数据成功");
				dataStat.put("msgCode", "302");
				dataStat.put("field", null);
				jsonStat.put("data", dataStat);
			}
			
			//return JsonConvertUtil.toJSONString(null,jsonStat);//jsonStat.toJSONString();
			return JSONObject.toJSONString(jsonStat, SerializerFeature.WriteMapNullValue);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	

}
